package com.djq.hhc.controller;

import com.djq.hhc.holder.UserHolder;
import com.djq.hhc.model.credit.CreditInfo;
import com.djq.hhc.result.Result;
import com.djq.hhc.service.CreditInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/03/05/下午 5:01
 * @Description:
 */

@RestController
@RequestMapping(value = "/credit/creditInfo")
public class CreditInfoController {

    @Autowired
    private CreditInfoService creditInfoService;

    @GetMapping("getCreditByUserId/{id}")
    public Result getCreditByUserId(@RequestHeader("Authorization") String token, @PathVariable String id) {
        Long userId = Long.valueOf(id);
        return creditInfoService.getByUserId(userId);
    }

    @GetMapping("getCredit/{userId}")
    public Integer getCredit(@RequestHeader("Authorization") String token, @PathVariable String userId) {
        Long id = Long.valueOf(userId);
        CreditInfo creditInfo = creditInfoService.query().eq("user_id", id).one();
        return creditInfo.getCredit();
    }

    @PutMapping("discountCredit/{price}/{preCredit}")
    public boolean discountCredit(@RequestHeader("Authorization") String token, @PathVariable Integer price, @PathVariable Integer preCredit) {
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            return false;
        }
        return creditInfoService.update().eq("user_id", userId).eq("credit", preCredit).setSql("credit = credit -" + price).gt("credit", price - 1).update();
    }
}
